# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def convertBST(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        def helper(root, sum):
            if not root:
                return root
            sub = 0
            # 1。 转换右子树
            if root.right:
                sub = helper(root.right, sum)
            # 2。 更新当前节点
            root.val = root.val + (sub if root.right else sum)
            # 3。 转换左子树
            if root.left:
                sub = helper(root.left, root.val)
                return sub
            else:
                return root.val
        helper(root, 0)
        return root